package com.qinge.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qinge.blog.dao.BlogEssayDao;
import com.qinge.blog.entity.BlogEssay;
import com.qinge.blog.entity.BlogEssayExample;
import com.qinge.blog.utils.CurrentUserUtil;
import com.qinge.blog.vo.paging.PagingReqVO;
import org.springframework.stereotype.Service;
import com.qinge.blog.service.BlogEssayService;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author QDW
 * @date 2022-05-02 23:38:51
 * @description BlogEssay service层实现类
 */
@Service
public class BlogEssayServiceImpl  implements BlogEssayService {
    @Resource
    BlogEssayDao essayDao;

    @Override
    public void add(BlogEssay... blogEssays) {
        for (BlogEssay eassy: blogEssays) {
            eassy.setUserId(CurrentUserUtil.getUserId());
        }

        essayDao.batchInsert(Arrays.asList(blogEssays));
    }

    @Override
    public void addByList(List<BlogEssay> blogEssays) {
        for (BlogEssay eassy: blogEssays) {
            eassy.setUserId(CurrentUserUtil.getUserId());
        }

        essayDao.batchInsert(blogEssays);
    }

    @Override
    public void removeById(String id) {
        essayDao.deleteByPrimaryKey(id);
    }

    @Override
    public void removeBatchByIds(List<String> ids) {
        BlogEssayExample example=new BlogEssayExample();
        BlogEssayExample.Criteria criteria=example.createCriteria();

        criteria.andIdIn(ids);

        essayDao.deleteByExample(example);
    }

    @Override
    public void update(BlogEssay blogEssay) {
        essayDao.upsert(blogEssay);
    }

    @Override
    public void upsert(BlogEssay blogEssay) {
        essayDao.upsert(blogEssay);
    }

    @Override
    public BlogEssay findById(String id) {
        return essayDao.selectByPrimaryKey(id);
    }

    @Override
    public List<BlogEssay> findByIds(List<String> ids) {
        BlogEssayExample example=new BlogEssayExample();
        BlogEssayExample.Criteria criteria=example.createCriteria();

        criteria.andIdIn(ids);

        return essayDao.selectByExample(example);
    }

    @Override
    public PageInfo<BlogEssay> findAll() {
        return paging(new PagingReqVO<BlogEssay>());
    }

    @Override
    public PageInfo<BlogEssay> findAll(PagingReqVO<BlogEssay> pagingReqVO) {
        return paging(pagingReqVO);
    }

    @Override
    public PageInfo<BlogEssay> paging(PagingReqVO<BlogEssay> pagingReqVO) {
        PageHelper.startPage(pagingReqVO);

        BlogEssayExample example=new BlogEssayExample();
        BlogEssayExample.Criteria criteria=example.createCriteria();

        if(!CurrentUserUtil.isAdmin()){
            criteria.andUserIdEqualTo(CurrentUserUtil.getUserId());
        }

        List<BlogEssay> list=essayDao.selectByExample(example);

        return new PageInfo<>(list);
    }
}

